import { 
    CssBaseline,
} from '@mui/material';
import Navbar from '../components/Navbar';
import categoryOptions from './category.json'
import { Link, useLocation, useNavigate } from 'react-router-dom';
import SearchIcon from '@mui/icons-material/Search';
import React, { useState, useEffect } from 'react';
import {
  Container,
  Grid,
  Paper,
  Typography,
  Avatar,
  Tabs,
  Tab,
  Box,
  Chip,
  Divider,
  AppBar,
  Toolbar,
  Button,
  TextField,
  IconButton,
  Select,
  MenuItem
} from '@mui/material';
import SeedList from '../components/SeedList';
import { getUserInfo } from '../api/user'; // 根据你的路径调整
import { navigationItems } from '../App';




function useQuery() {
  return new URLSearchParams(useLocation().search);
}
function Seeds() {
  const navigate = useNavigate();
  const query = useQuery();
  const seed_name = query.get('name'); // 获取传过来的关键词
  const [user, setUser] = useState(null);
const [userInfo, setUserInfo] = useState({
  avatar: '/default/avatar.png',
  username: '游客',
}); 
    const handleLoginClick = () => {
      navigate("/login"); 
    };
  const [category, setCategory] = useState('音乐');
  const [firstType, setFirstType] = useState('');
  const [secondType, setSecondType] = useState('');
  const [thirdType, setThirdType] = useState('');
  const [fourthType, setFourthType] = useState('');
  const [name,setName] = useState(seed_name||'');
  const [inputValue, setInputValue] = useState(''); // 实时输入内容
  const [searchType,setSearchType] = useState('simple')
 const userToken = localStorage.getItem('token');
// console.log("从 localStorage 拿到的 userId:", userId);

  useEffect(() => {
    if (!userToken) {
      alert('请先登录！');
      navigate('/login');
      return;
    }

    getUserInfo(userToken)
  .then(res => {
    if (res.data) {
      console.log('用户信息:', res.data);
      setUserInfo(res.data);
    } else {
      setUserInfo({
        avatar: '/default/avatar.png',
        username: '游客',
      });
    }
  })
  .catch(err => {
    console.error('获取用户信息失败:', err);
    setUserInfo({
      avatar: '/default/avatar.png',
      username: '游客',
    });
  });

  }, [userToken, navigate]);
  const handleSearch = () => {
    setName(inputValue); // 点击按钮才设置 name
    console.log("搜索关键词：", inputValue);
    console.log("搜索类型：", searchType);
    // 你可以在这里添加实际的搜索请求逻辑
  };
  // 处理标签的切换逻辑
  const handleFirstTypeToggle = (type) => {
    setFirstType(firstType === type ? '' : type);
  };
  
  const handleSecondTypeToggle = (type) => {
    setSecondType(secondType === type ? '' : type);
  };
  
  const handleThirdTypeToggle = (type) => {
    setThirdType(thirdType === type ? '' : type);
  };
  
  const handleFourthTypeToggle = (type) => {
    setFourthType(fourthType === type ? '' : type);
  };
  
  const location = useLocation()
  return (
    <div className='seeds'>
      <CssBaseline />
            <Navbar shown={1}/>
            <Container
                    maxWidth="false"
                    sx={{
                      backdropFilter: 'blur(4px)',
                      backgroundColor: 'rgba(255,255,255,0.6)',
                      borderRadius: 3,
                      p: 2,
                      mt: 3,
                    }}
                  >
            
                  <Box sx={{ maxWidth: '1400px', mx: 'auto' }}>
                    <Tabs
                        value={location.pathname}
                        indicatorColor="secondary"
                        textColor="secondary"
                        variant="scrollable"
                        scrollButtons="auto"
                        sx={{
                          borderBottom: '2px solid #f3e5f5',
                          mb: 2,
                          '& .MuiTab-root': {
                            transition: 'all 0.3s ease-in-out',
                          },
                          '& .Mui-selected': {
                            color: '#8e24aa',
                            fontWeight: 'bold',
                          },
                          '& .MuiTabs-indicator': {
                            height: 3,
                            backgroundColor: '#ce93d8',
                            borderRadius: 2,
                          }
                        }}
                      >
            
                      {navigationItems.map((item) => (
                        <Tab
                          key={item.path}
                          label={item.label}
                          value={item.path}
                          component={Link}
                          to={item.path}
                          sx={{
                            minWidth: 100,
                            borderRadius: 2,
                            mx: 0.5,
                            transition: 'all 0.3s',
                            color: '#8e24aa',
                            '&:hover': {
                              backgroundColor: '#ffe0f0',
                              color: '#d81b60',
                            },
                            '&.Mui-selected': {
                              fontWeight: 'bold',
                              color: '#d81b60',
                              backgroundColor: '#fff0f5',
                            },
                          }}
                        />
                      ))}
                    </Tabs>
                    </Box>
                  </Container>
      <Container maxWidth="lg" sx={{ paddingTop: 3 }}>
        <Paper elevation={3} sx={{ p: 3, mb: 3 }}>
          <Grid container spacing={3}>
<Grid item sx={{ flexBasis: 300, flexGrow: 0, maxWidth: 150 }}>
            <Box
              sx={{
                width: '100%',
                bgcolor: '#f9f9fb',
                borderRadius: 3,
                boxShadow: 3,
                p: 3,
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
              }}
            >
              <Avatar
                sx={{
                  width: 100,
                  height: 100,
                  boxShadow: 2,
                  border: '3px solid white',
                  mb: 1
                }}
                src={userInfo.avatar}
              />
              <Typography variant="h6" gutterBottom>{userInfo.username}</Typography>

              <Chip
                label={`LV.${userInfo.level}`}
                color="primary"
                size="small"
                sx={{ mb: 2 }}
              />

              <Divider sx={{ width: '100%', mb: 2 }} />

              <Box sx={{ width: '100%' }}>
                <Typography variant="body2" sx={{ mb: 0.5 }}>上传量：<strong>{userInfo.upload}</strong></Typography>
                <Typography variant="body2" sx={{ mb: 0.5 }}>下载量：<strong>{userInfo.download}</strong></Typography>
                <Typography variant="body2" sx={{ mb: 0.5 }}>分享率：<strong>{userInfo.ratio}</strong></Typography>
                <Typography variant="body2" sx={{ mb: 0.5 }}>积分：<strong>{userInfo.score}</strong></Typography>
                <Typography variant="body2" sx={{ mb: 0.5 }}>杨桃：<strong>{userInfo.yangtao}</strong></Typography>
              </Box>
            </Box>
          </Grid>

             <Grid item xs={12} md={8}>
  <div
    style={{
      display: 'flex',
      alignItems: 'center',
      flexWrap: 'wrap', // 如果太长就自动换行
      gap: '8px',        // 控件之间的间距
    }}
  >
    {/* 输入框 */}
    <TextField
      variant="outlined"
      size="small"
      value={inputValue}
      placeholder="搜索关键词"
      style={{ width: '600px' }}
      onChange={(e) => setInputValue(e.target.value)}
    />

    {/* 搜索类型选择 */}
    <Select
      value={searchType}
      onChange={(e) => setSearchType(e.target.value)}
      size="small"
      style={{ width: '120px' }}
    >
      <MenuItem value="ai">模糊搜索(ai)</MenuItem>
      <MenuItem value="simple">精准搜索</MenuItem>
    </Select>

    {/* 搜索按钮 */}
    <Button
      variant="contained"
      color="primary"
      onClick={handleSearch}
      style={{ height: '40px' }}
    >
      搜索
    </Button>
  </div>
            {/* 一级 Tabs 分类 */}
            <Tabs
              value={category}
              onChange={(e, newValue) => {
                setCategory(newValue);
              }}
              textColor="primary"
              indicatorColor="primary"
              variant="scrollable"
              scrollButtons="auto"
              sx={{ mb: 2 }}
            >
              {Object.keys(categoryOptions).map((cat) => (
                <Tab
                  key={cat}
                  label={cat}
                  value={cat}
                  sx={{ '&.Mui-selected': { fontWeight: 'bold' } }}
                />
              ))}
            </Tabs>
            <Box 
              display="flex"
              flexWrap="wrap"
              maxWidth="900px"  
              gap={1}
              sx={{ mb: 2 }}
            >
              {/* 二级子分类，每个单独占一行 */}
              <Box display="flex" alignItems="center" flexWrap="wrap" gap={1} sx={{ mb: 2 }}>
                <Typography variant="subtitle1" sx={{ mr: 2, whiteSpace: 'nowrap' }}>
                  {categoryOptions[category]['子分类'][0]}
                </Typography>
                 <Chip
        key="全部"
        label="全部"
        clickable
        color={firstType === '' ? 'primary' : 'default'}
        variant={firstType === '' ? 'filled' : 'outlined'}
        onClick={() => handleFirstTypeToggle('')}
      />
                {categoryOptions[category]?.[categoryOptions[category]['子分类'][0]].map((sub) => (
                  <Chip
                    value={name}
                    key={sub}
                    label={sub}
                    clickable
                    color={firstType === sub ? 'primary' : 'default'}
                    variant={firstType === sub ? 'filled' : 'outlined'}
                    onClick={() => handleFirstTypeToggle(sub)}
                  />
                ))}
              </Box>
              <Box display="flex" alignItems="center" flexWrap="wrap" gap={1} sx={{ mb: 2 }}>
                <Typography variant="subtitle1" sx={{ mr: 2, whiteSpace: 'nowrap' }}>
                  {categoryOptions[category]['子分类'][1]}
                </Typography>
                <Chip
        key="全部"
        label="全部"
        clickable
        color={secondType === '' ? 'primary' : 'default'}
        variant={secondType === '' ? 'filled' : 'outlined'}
        onClick={() => handleSecondTypeToggle('')}
      />
                {categoryOptions[category]?.[categoryOptions[category]['子分类'][1]].map((sub) => (
                  <Chip
                    key={sub}
                    label={sub}
                    clickable
                    color={secondType === sub ? 'primary' : 'default'}
                    variant={secondType === sub ? 'filled' : 'outlined'}
                    onClick={() => handleSecondTypeToggle(sub)}
                  />
                ))}
              </Box>
              <Box display="flex" alignItems="center" flexWrap="wrap" gap={1} sx={{ mb: 2 }}>
                <Typography variant="subtitle1" sx={{ mr: 2, whiteSpace: 'nowrap' }}>
                  {categoryOptions[category]['子分类'][2]}
                </Typography>
                <Chip
        key="全部"
        label="全部"
        clickable
        color={thirdType=== '' ? 'primary' : 'default'}
        variant={thirdType === '' ? 'filled' : 'outlined'}
        onClick={() => handleThirdTypeToggle('')}
      />
                {categoryOptions[category]?.[categoryOptions[category]['子分类'][2]].map((sub) => (
                  <Chip
                    key={sub}
                    label={sub}
                    clickable
                    color={thirdType === sub ? 'primary' : 'default'}
                    variant={thirdType === sub ? 'filled' : 'outlined'}
                    onClick={() => handleThirdTypeToggle(sub)}
                  />
                ))}
              </Box>
              <Box display="flex" alignItems="center" flexWrap="wrap" gap={1} sx={{ mb: 2 }}>
                <Typography variant="subtitle1" sx={{ mr: 2, whiteSpace: 'nowrap' }}>
                  {categoryOptions[category]['子分类'][3]}
                </Typography>
                <Chip
        key="全部"
        label="全部"
        clickable
        color={fourthType === '' ? 'primary' : 'default'}
        variant={fourthType === '' ? 'filled' : 'outlined'}
        onClick={() => handleFourthTypeToggle('')}
      />
                {categoryOptions[category]?.[categoryOptions[category]['子分类'][3]].map((sub) => (
                  <Chip
                    key={sub}
                    label={sub}
                    clickable
                    color={fourthType === sub ? 'primary' : 'default'}
                    variant={fourthType === sub ? 'filled' : 'outlined'}
                    onClick={() => handleFourthTypeToggle(sub)}
                  />
                ))}
              </Box>
            </Box>
          </Grid>
        </Grid>
      </Paper>

      <Paper elevation={3} sx={{ p: 2 }}>
        <SeedList category={category} first={firstType} second={secondType} third={thirdType} fourth={fourthType} name={name} type={searchType}/>
      </Paper>
      </Container>
    </div>
  );
}

export default Seeds;
